package books4africa

import org.springframework.dao.DataIntegrityViolationException
import grails.converters.*


class BooksController {
	
	def booksService
	
	static navigation = [
		[group:'tabs', action:'list', title:'Books', order:1],
		]
	
	def index = {
		redirect(action:list)
	}
	
	// return list of books
	def list = { 		
		
		params.max = Math.min(params.max ? params.int('max') : 10, 100)
		[booksInstanceList: Books.list(params), booksInstanceTotal: Books.count()]
	
		
	}
	
	def restList(){
		def thisList = Books.list()
		withFormat{
			html {[bookInstanceList:thisList]}
			xml{render thisList as XML}
		}
	}
	
	def create() {
		[booksInstance: new Books(params)]
	}
	
	def save() {
		def booksInstance
		try{
			booksInstance = booksService.saveBook(params)
		} catch (BooksException e){
			flash.message = e.message
		}
		
		redirect(action: "list")
	}
	
	
	def restShow(){
		Books book = Books.get(params.id)
		
		
		if (book){
			withFormat{
				html book:bookInstance
				xml{render book as XML}
			}
		}
	}
	
	def restSave(){
		
		booksService.saveBookRest(request)
	}
	
	def show() {
		def booksInstance = Books.get(params.id)
		if (!booksInstance) {
			flash.message = message(code: 'default.not.found.message', args: [message(code: 'Books.label', default: 'Books'), params.id])
			redirect(action: "list")
			return
		}

		[booksInstance: booksInstance]
	}
	
	def edit() {
		def booksInstance = Books.get(params.id)
		if (!booksInstance) {
			flash.message = message(code: 'default.not.found.message', args: [message(code: 'Books.label', default: 'Books'), params.id])
			redirect(action: "list")
			return
		}

		[booksInstance: booksInstance]
	}
	
	def update() {
		
		def booksInstance
		
		try {
			booksInstance = booksService.updateBook(params)
		}catch (BooksException e){
			flash.message = e.message
			render(view: "edit", model: [booksInstance: booksInstance])
		} catch (ValidationException v){
			flash.message = v.message
			render(view:"edit", model:[booksInstance:booksInstance])
		}
		
	}
	
	def restUpdate(){
		booksService.restUpdate(request)
		
	}
	
	def restDelete(){
		Books book = Books.get(params.id)
		
		book.delete()
	}
	
	private def failedValidation(book, status){
		response.status = status
		render contentType: 'application/xml', {
			errors {
				book?.errors?.fieldErrors?.each { err ->
					field(err.field)
					message(g.message(error:err))	
				
				}	
			}
		}
	}
	
	
}
